package com.efounder.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.ospmobilelib.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.view.titlebar.AbTitleBar;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SimpleWebFragment_url extends Activity {

	private static final String TAG = "SimpleWebFragment";
	private StubObject mMenuItem;
	private String titleStr;
	// CustomProgressDialog dialog;
	private View rootView;// 缓存Fragment view
	AbTitleBar title;
	String url;
	String titleName;
	String webUrl ;

	/*
	 * public SimpleWebFragment_url(String title,String url) { this.titleStr =
	 * title; this.url= url; }
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_webview);
		
		
		/*
		 * title.setTitleTextColor(Color.WHITE);
		 * title.setLogo(R.drawable.button_selector_back);
		 * 
		 * title.setTitleText("测试"); title.setVisibility(View.VISIBLE);
		 * title.getLogoView().setVisibility(View.VISIBLE);
		 * title.setLogo(R.drawable.back_n);
		 * title.getLogoView().setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub
		 * //SimpleWebFragment_url.this.getActivity().getSupportFragmentManager
		 * ().popBackStack(); SimpleWebFragment_url.this.finish(); } });
		 */
		// rootView = inflater.inflate(R.layout.test_webview, container, false);
		// dialog = new CustomProgressDialog(getActivity());

		// View rootView = inflater.inflate(R.layout.test_webview, container,
		// false);
		// Hashtable menuTable = mMenuItem.getStubTable();
		/*
		 * String param = (String) menuTable.get("param"); String value =
		 * (String) menuTable.get("value");
		 */
		webUrl = "http://www.baidu.com";
		webUrl = getIntent().getStringExtra("url");
		titleName = getIntent().getStringExtra("title");
		
		
		RelativeLayout include = (RelativeLayout) findViewById(R.id.include);
		include.setBackgroundResource(R.color.red);
		TextView title = (TextView)findViewById(R.id.fragmenttitle);
		title.setText(titleName);
		title.setTextColor(Color.WHITE);
		LinearLayout leftbacklayout = (LinearLayout) findViewById(R.id.leftbacklayout);
		leftbacklayout.setVisibility(View.VISIBLE);
		/*Button backButton = (Button) findViewById(R.id.backButton);
		backButton.setVisibility(View.VISIBLE);
		backButton.setBackgroundResource(R.drawable.fanhuiarrow);*/

		leftbacklayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// SimpleWebFragment_url.this.getSupportFragmentManager().popBackStack();
				SimpleWebFragment_url.this.finish();
			}
		});
		
		
		

		final WebView web = (WebView) findViewById(R.id.mywebview);

		/*** 打开本地缓存提供JS调用 **/
		web.getSettings().setDomStorageEnabled(true);
		// Set cache size to 8 mb by default. should be more than enough
		web.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
		// This next one is crazy. It's the DEFAULT location for your app's
		// cache
		// But it didn't work for me without this line.
		// UPDATE: no hardcoded path. Thanks to Kevin Hawkins
		String appCachePath = getApplicationContext().getCacheDir()
				.getAbsolutePath();
		web.getSettings().setAppCachePath(appCachePath);
		web.getSettings().setAllowFileAccess(true);
		web.getSettings().setAppCacheEnabled(true);
		
		
		
		

		
				 
	    web.getSettings().setJavaScriptEnabled(true);
		web.setWebViewClient(new webClient());
		//web.loadUrl(String.valueOf(webUrl));
		final String wholeJS = getFromAssets("self_define.js");
		web.loadUrl(webUrl);
		web.post(new Runnable() {
		    @Override
		    public void run() {
		    	
				web.loadUrl("javascript:" + wholeJS);
		    }
		});
		/*new Thread(){
			public void run(){
				//你想做的事情
				String baseUrl="file:///android_asset/mobileinit.js";
				String ss =  doGetConnect(String.valueOf(baseUrl));
				System.out.println(ss);
				web.loadDataWithBaseURL(String.valueOf(webUrl), doGetConnect(String.valueOf(baseUrl)), "text/html", "utf-8", null);
				
				web.loadUrl(webUrl);
				web.loadUrl("javascript:" + wholeJS);
			
				
			};
		}.start();*/
		
		web.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					if (keyCode == KeyEvent.KEYCODE_BACK && web.canGoBack()) { // 表示按返回键
																				// 时的操作
						web.goBack(); // 后退
						return true; // 已处理
					}
				}
				return false;
			}

		});
		// web.setWebChromeClient(new MyWebChromeClient());
		// web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		// 缓存的rootView需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		// ViewGroup parent = (ViewGroup) rootView.getParent();
		// if (parent != null) {
		// parent.removeView(rootView);
		// }
	}

	/*
	 * @Override public void onActivityCreated(Bundle savedInstanceState) {
	 * 
	 * super.onActivityCreated(savedInstanceState);
	 * 
	 * }
	 * 
	 * @Override public void onAttach(Activity activity) {
	 * super.onAttach(activity); }
	 * 
	 * @Override public View onCreateView(LayoutInflater inflater, ViewGroup
	 * container, Bundle savedInstanceState) { rootView =
	 * inflater.inflate(R.layout.test_webview, container, false); // dialog =
	 * new CustomProgressDialog(getActivity());
	 * 
	 * // View rootView = inflater.inflate(R.layout.test_webview, container, //
	 * false); //Hashtable menuTable = mMenuItem.getStubTable(); Object webUrl =
	 * url; String param = (String) menuTable.get("param"); String value =
	 * (String) menuTable.get("value"); // webUrl = "http://www.baidu.com";
	 * 
	 * final WebView web = (WebView) rootView.findViewById(R.id.mywebview);
	 * web.getSettings().setJavaScriptEnabled(true); web.setWebViewClient(new
	 * webClient()); web.loadUrl(String.valueOf(webUrl));
	 * web.setOnKeyListener(new OnKeyListener() {
	 * 
	 * @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if
	 * (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode ==
	 * KeyEvent.KEYCODE_BACK && web.canGoBack()) { //表示按返回键 时的操作 web.goBack();
	 * //后退 return true; //已处理 } } return false; }
	 * 
	 * }); // web.setWebChromeClient(new MyWebChromeClient()); //
	 * web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //
	 * 缓存的rootView需要判断是否已经被加过parent， //
	 * 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。 // ViewGroup parent =
	 * (ViewGroup) rootView.getParent(); // if (parent != null) { //
	 * parent.removeView(rootView); // } return rootView; }
	 */
	private class webClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// dialog.show();
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			// dialog.dismiss();
			LoadingDataUtilBlack.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			// dialog.show();
			LoadingDataUtilBlack.show(SimpleWebFragment_url.this);
		}

		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			// handler.cancel(); 默认的处理方式，WebView变成空白页
			handler.proceed();// 接受证书
			LoadingDataUtilBlack.dismiss();
			// handleMessage(Message msg); 其他处理
		}

	}

	@Override
	public void onStart() {
	/*	title = getTitleBar();
		title.setTitleText(titleName);
		title.setVisibility(View.VISIBLE);
		title.setTitleBarBackground(R.color.red);
		title.getLogoView().setVisibility(View.VISIBLE);
		title.setLogo(R.drawable.fanhuiarrow);
		LinearLayout.LayoutParams ll = (LayoutParams) title
				.getTitleTextLayout().getLayoutParams();
		 ll.setMargins(10, 40, 0, 40); 
		Resources r = getResources();
		float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
				r.getDisplayMetrics());
		ll.height = (int) px;
		title.getTitleTextLayout().setLayoutParams(ll);
		// title.getLogoView().setLayoutParams(ll);

		title.getLogoView().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// SimpleWebFragment_url.this.getSupportFragmentManager().popBackStack();
				SimpleWebFragment_url.this.finish();
			}
		});
		title.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);*/
		super.onStart();
	}

	public void onPause() {
		super.onPause();
		//title.setVisibility(View.GONE);
	}
	private String doGetConnect(String url){
		String result = "";
		InputStream is = null;
		HttpGet httpRequest=new HttpGet(url);
		try {
		HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
		if(httpResponse.getStatusLine().getStatusCode()==200){ //正确

		is = httpResponse.getEntity().getContent();
		byte[] data = new byte[1024];
		int n = -1;
		ByteArrayBuffer buf = new ByteArrayBuffer(10*1024);
		while ((n = is.read(data)) != -1)
		buf.append(data, 0, n);
		result= new String(buf.toByteArray(), HTTP.UTF_8);
		Log.v("result==", result);
		is.close();
		return result;
		}
		else {Log.v("tip==", "error response code");}
		} catch (Exception e) {
		e.printStackTrace();
		}
		return null;
		}
	
	public String getFromAssets(String fileName) {
		InputStreamReader inputReader = null;
		try {
			inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
			BufferedReader bufReader = new BufferedReader(inputReader);
			String line = "";
			String Result = "";
			while ((line = bufReader.readLine()) != null)
				Result += line;
			return Result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputReader != null) {
				try {
					inputReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
